from django.shortcuts import render
from django.http import HttpResponseRedirect,HttpResponse
from .models import *
from django.db.utils import *
import json
# Create your views here.

# 增加楼房的表格
def proper_add(request):
    room = Room.objects.all()
    context = {'context': room}
    return render(request, 'tower/proper_add.html', context)
# 增加楼房
def add_building(request):
    """
        @author:吕琛琛
        @date:2018/10/11

        提交方式 ：POST
        提交数据格式 ：{'add_tower_name':'xxx'}
    """
    if request.method == 'GET':
        return HttpResponse(json.dumps({'message': '访问模式应该为 POST'}))
    elif request.method == 'POST':
        try:
            info = dict(request.POST)['add_tower_name']
        except KeyError:
            return HttpResponse(json.dumps({'message': "提交信息格式不对，或者键不是'add_tower_name'"}))
        else:
            add_list = []
            for i in info:
                if i.replace(' ', '') != '':
                    add_list.append(Tower(tower_name=i.replace(' ','')))
            if not add_list:
                return HttpResponse(json.dumps({'message': '楼名不能为空'}))
            try:
                Tower.objects.bulk_create(add_list)
            except IntegrityError:
                return HttpResponse(json.dumps({'message': '楼名重复'}))
            else:
                return HttpResponse(json.dumps({'message': '楼房添加成功'}))

# 增加楼层
def add_floor(request):
    """
        @author:吕琛琛
        @date:2018/10/11

        提交方式 ：POST
        提交数据格式 ：{'add_tower_name':'xxx'}
    """
    if request.method == 'GET':
        return HttpResponse(json.dumps({'message': '访问模式应该为 POST'}))
    elif request.method == 'POST':
        try:
            # 将输入的空格去除掉
            info = request.POST['add_tower_name'].strip()
        except KeyError:
            return HttpResponse(json.dumps({'message': "提交信息格式不对，或者键不是'add_tower_name'"}))
        else:
            # 当输入空格时
            if info == '':
                return HttpResponse(json.dumps({'message': '添加的楼房名不能为空'}))
            else:
                # 从数据库中搜索楼房
                try:
                    tn = Tower.objects.get(tower_name=info)
                # 若没有搜索到楼房
                except Tower.DoesNotExist:
                    return HttpResponse(json.dumps({'message': '楼房不存在'}))
                # 若搜索到楼房,继续添加楼层
                else:
                    try:
                        info_1 = dict(request.POST)['add_floor_num']
                    except KeyError:
                        return HttpResponse(json.dumps({'message': "提交信息格式不对，或者键不是'add_floor_num'"}))
                    else:
                        add_list = []
                        for i in info_1:
                            if i.replace(' ', '') != '':
                                try:
                                    tn.floor_set.get(floor_num=i) 
                                except Floor.DoesNotExist:
                                    add_list.append(Floor(floor_num=i, tower=tn))
                                else:
                                    return HttpResponse(json.dumps({'message': '楼层重复'}))
                        if not add_list:
                            return HttpResponse(json.dumps({'message': '楼层不能为空'}))
                        Floor.objects.bulk_create(add_list)
                        return HttpResponse(json.dumps({'message': '楼层添加成功'}))


# 增加房间
def add_room(request):
    """
        @author:吕琛琛
        @date:2018/10/11

        提交方式 ：POST
        提交数据格式 ：{'add_tower_name':'xxx'}
    """
    if request.method == 'GET':
        return HttpResponse(json.dumps({'message': '访问模式应该为 POST'}))
    elif request.method == 'POST':
        try:
            # 将输入的空格去除掉
            info = request.POST['add_tower_name'].strip()
        except KeyError:
            return HttpResponse(json.dumps({'message': "提交信息格式不对，或者键不是'add_tower_name'"}))
        else:
            # 当输入空格时
            if info == '':
                return HttpResponse(json.dumps({'message': '添加的楼房名不能为空'}))
            else:
                # 从数据库中搜索楼房
                try:
                    tn = Tower.objects.get(tower_name=info)
                # 若楼房没有搜索到
                except Tower.DoesNotExist:
                    return HttpResponse(json.dumps({'message': '楼房不存在'}))
                # 若楼房搜索到,继续搜索楼层
                else:
                    try:
                        info_1 = request.POST['add_floor_num'].strip()
                    except KeyError:
                        return HttpResponse(json.dumps({'message': "提交信息格式不对，或者键不是'add_floor_num'"}))
                    else:
                        if info_1 == '':
                            return HttpResponse(json.dumps({'message': '添加的楼层数不能为空'}))
                        else:
                            # 从数据库中搜索楼层
                            try:
                                fl = tn.floor_set.get(floor_num=info_1)
                            # 若没有搜索到楼层
                            except Floor.DoesNotExist:
                                return HttpResponse(json.dumps({'message': '楼层不存在'}))
                            # 若搜索到楼层
                            else:
                                try:
                                    info_2 = dict(request.POST)['add_room_num']
                                except KeyError:
                                    return HttpResponse(json.dumps({'message': "提交信息格式不对，或者键不是'add_room_num'"}))
                                else:
                                    add_list = []
                                    for i in info_2:
                                        if i.replace(' ', '') != '':
                                            add_list.append(Room(room_num=i, floor=fl))
                                    if not add_list:
                                        return HttpResponse(json.dumps({'message': '添加的房间号不能为空'}))
                                    try:
                                        Room.objects.bulk_create(add_list)
                                    except IntegrityError:
                                        return HttpResponse(json.dumps({'message': '房间重复'}))
                                    else:
                                        return HttpResponse(json.dumps({'message': '房间添加成功'}))


# 检测代码
def test_tower(request):
    return render(request, 'tower/add_building.html')


# 删除楼房
def del_tower(request):
    """
        @author:赵泽华
        @date:2018/10/12

        提交方式 ：POST
        提交数据格式 ：{'add_tower_name':'xxx'}
    """
    if request.method == 'GET':
        return HttpResponse(json.dumps({'message': '不接受GET请求'}))
    elif request.method == 'POST':
        info = dict(request.POST)
        try:
            q1 = Tower.objects.get(tower_name=info['add_tower_name'][0])
        except Tower.DoesNotExist:
            return HttpResponse(json.dumps({'message': '没有这楼'}))
        except KeyError:
            return HttpResponse(json.dumps({'message': '输入错误'}))
        else:
            q1.delete()
            return HttpResponse(json.dumps({'message': '删除成功'}))


# 删除楼层
def del_floor(request):
    """
        @author:赵泽华
        @date:2018/10/12

        提交方式 ：POST
        提交数据格式 ：{'add_tower_name':'xxx'}
    """
    if request.method == 'GET':
        return HttpResponse(json.dumps({'message': '不接受GET请求'}))
    elif request.method == 'POST':
        info = dict(request.POST)
        try:
            q1 = Tower.objects.get(tower_name=info['add_tower_name'][0])
        except Tower.DoesNotExist:
            return HttpResponse(json.dumps({'message': '没有这楼'}))
        except KeyError:
            return HttpResponse(json.dumps({'message': '输入错误'}))
        else:
            try:
                q2 = q1.floor_set.get(floor_num=info['add_floor_num'][0])
            except Floor.DoesNotExist:
                return HttpResponse(json.dumps({'message': '没有这层'}))
            except KeyError:
                return HttpResponse(json.dumps({'message': '输入错误'}))
            else:
                q2.delete()
                return HttpResponse(json.dumps({'message': '删除({})楼层成功'.format(info['add_floor_num'][0])}))


# 删除房间
def del_room(request):
    """
        @author:赵泽华
        @date:2018/10/12

        提交方式 ：POST
        提交数据格式 ：{'add_tower_name':'xxx'}
    """
    if request.method == 'GET':
        return HttpResponse(json.dumps({'message': '不接受get请求'}))
    elif request.method == 'POST':
        info = dict(request.POST)
        try:
            q1 = Tower.objects.get(tower_name=info['add_tower_name'][0])
        except Tower.DoesNotExist:
            return HttpResponse(json.dumps({'message': '没有这楼'}))
        except KeyError:
            return HttpResponse(json.dumps({'message': '输入错误'}))
        else:
            try:
                q2 = q1.floor_set.get(floor_num=info['add_floor_num'][0])
            except Floor.DoesNotExist:
                return HttpResponse(json.dumps({'message': '没有这层'}))
            except KeyError:
                return HttpResponse(json.dumps({'message': '输入错误'}))
            else:
                try:
                    q3 = q2.room_set.get(room_num=info['add_room_num'][0])
                except Room.DoesNotExist:
                    return HttpResponse(json.dumps({'message': '没有这房间'}))
                except KeyError:
                    return HttpResponse(json.dumps({'message': '输入错误'}))
                else:
                    q3.delete()
                    return HttpResponse(json.dumps({'message': '删除({})成功'.format(info['add_room_num'][0])}))


# 修改楼房
def change_tower(request):
    """
    @auther: 辛光华
    @date: 2018/10/11
    提交方式: POST
    提交数据格式: #####这地方看下数据库!!!!!!!!
                {'tower_name': '宿舍楼', 'new_tower_name': '黄鹤楼'}
    """
    if request.method == "POST":
        info = dict(request.POST)
        print(info)
        try:
            Tower.objects.get(tower_name=info["tower_name"][0])
        except Tower.DoesNotExist:
            return HttpResponse(json.dumps({'message': "查无此楼"}))
        else:
            Tower.objects.filter(tower_name=info['tower_name'][0]).update(tower_name=info['new_tower_name'][0])
            return HttpResponse(json.dumps({'message': "楼名修改成功"}))
    else:
        return HttpResponse(json.dumps({'message': '不接受get请求'}))


# 修改楼层
def change_floor(request):
    """
        @auther: 辛光华
        @date: 2018/10/11
        提交方式: POST
        提交数据格式: {   #####这地方看下数据库!!!!!!!!
                      'tower_name': '烂尾楼',
                      'floor_num': '5',
                      'new_tower_name': '黄鹤楼',
                      'new_floor_num': '8'}
        """
    if request.method == "POST":
        info = dict(request.POST)
        print(info)
        try:
            tw = Tower.objects.get(tower_name=info['tower_name'][0])
            fl = tw.floor_set.get(floor_num=info['floor_num'][0])
        except Tower.DoesNotExist:
            return HttpResponse(json.dumps({'message': "查无此楼"}))
        except Floor.DoesNotExist:
            return HttpResponse(json.dumps({'message': "这楼没这层"}))
        else:
            Tower.objects.filter(tower_name=info['tower_name'][0]).update(tower_name=info['new_tower_name'][0])
            tw.floor_set.filter(floor_num=info['floor_num'][0]).update(floor_num=info['new_floor_num'][0])
            return HttpResponse(json.dumps({'message': "楼层信息修改成功"}))
    else:
        return HttpResponse(json.dumps({'message': '不接受get请求'}))


# 修改房间
def change_room(request):
    """
        @auther: 辛光华
        @date: 2018/10/11
        提交方式: POST
        提交数据格式: {  #####这地方看下数据库!!!!!!!!
                       'tower_name': '观音楼',
                       'floor_num': '8',
                       'room_num': '888'
                       'new_tower_name': '11',
                       'new_floor_num': '22',
                       'new_room_num': '33',
                       }
    """
    if request.method == "POST":
        info = dict(request.POST)
        print(info)
        try:
            tw = Tower.objects.get(tower_name=info['tower_name'][0])
            fl = tw.floor_set.get(floor_num=info['floor_num'][0])
            rm = fl.room_set.get(room_num=info['room_num'][0])
        except Tower.DoesNotExist:
            return HttpResponse(json.dumps({'message': "查无此楼"}))
        except Floor.DoesNotExist:
            return HttpResponse(json.dumps({'message': "这楼没这层"}))
        except Room.DoesNotExist:
            return HttpResponse(json.dumps({'message': "这层没这屋"}))
        else:
            Tower.objects.filter(tower_name=info['tower_name'][0]).update(tower_name=info['new_tower_name'][0])
            tw.floor_set.filter(floor_num=info['floor_num'][0]).update(floor_num=info['new_floor_num'][0])
            fl.room_set.filter(room_num=info['room_num'][0]).update(room_num=info['new_room_num'][0])
            return HttpResponse(json.dumps({'message': "楼层信息修改成功"}))
    else:
        return HttpResponse(json.dumps({'message': '不接受get请求'}))


# 查询楼房
def inquire_tower(request):
    """
        @author:王江萌
        @date:2018/10/12

        提交方式 ：POST
        提交数据格式 ：{'add_tower_name':'xxx'}
    """
    if request.method == 'GET':
        return HttpResponse(json.dumps({'message': '不接受get请求'}))
    elif request.method == 'POST':
        info = dict(request.POST)
        try:
            Tower.objects.get(tower_name=info['add_tower_name'][0])
        except Tower.DoesNotExist:
            return HttpResponse(json.dumps({'message': '没有找到'}))
        except KeyError:
            return HttpResponse(json.dumps({'message': '输入错误'}))
        else:
            return HttpResponse(json.dumps({'message': '已找到({})'.format(info['add_tower_name'][0])}))


# 查询楼层
def inquire_floor(request):
    """
        @author:王江萌
        @date:2018/10/12

        提交方式 ：POST
        提交数据格式 ：{'add_tower_name':'xxx'}
    """
    if request.method == 'GET':
        return HttpResponse(json.dumps({'message': '不接受get请求'}))
    elif request.method == 'POST':
        info = dict(request.POST)
        try:
            t1 = Tower.objects.get(tower_name=info['add_tower_name'][0])
        except Tower.DoesNotExist:
            return HttpResponse(json.dumps({'message': '没有找到'}))
        except KeyError:
            return HttpResponse(json.dumps({'message': '输入错误'}))
        else:
            try:
                t1.floor_set.get(floor_num=info['add_floor_num'][0])
            except Floor.DoesNotExist:
                return HttpResponse(json.dumps({'message': '没有找到({}{}层)'.format(info['add_tower_name'][0],info['add_floor_num'][0])}))
            except KeyError:
                return HttpResponse(json.dumps({'message': '输入错误'}))
            else:
                return HttpResponse(json.dumps({'message': '已找到({}{}层)'.format(info['add_tower_name'][0],info['add_floor_num'][0])}))


# 查询房间
def inquire_room(request):
    """
        @author:王江萌
        @date:2018/10/12

        提交方式 ：POST
        提交数据格式 ：{'add_tower_name':'xxx'}
    """
    if request.method == 'GET':
        return HttpResponse(json.dumps({'message': '不接受请求'}))
    elif request.method == 'POST':
        info = dict(request.POST)
        try:
            t1 = Tower.objects.get(tower_name=info['add_tower_name'][0])
        except Tower.DoesNotExist:
            return HttpResponse(json.dumps({'message': '未找到({})楼'.format(info['add_tower_name'][0])}))
        except KeyError:
            return HttpResponse(json.dumps({'message': '输入错误'}))
        else:
            try:
                t2 = t1.floor_set.get(floor_num=info['add_floor_num'][0])
            except Floor.DoesNotExist:
                return HttpResponse(json.dumps({'message': '未找到({})层'.format(info['add_floor_num'][0])}))
            except KeyError:
                return HttpResponse(json.dumps({'message': '输入错误'}))
            else:
                try:
                    t2.room_set.get(room_num=info['add_room_num'][0])
                except Room.DoesNotExist:
                    return HttpResponse(json.dumps({'message': '未找到({}{}层{}房间)'.format(info['add_tower_name'][0],info['add_floor_num'][0],info['add_room_num'][0])}))
                except KeyError:
                    return HttpResponse(json.dumps({'message': '输入错误'}))
                else:
                    return HttpResponse(json.dumps({'message': '已找到({}{}层{}房间)'.format(info['add_tower_name'][0],info['add_floor_num'][0],info['add_room_num'][0])}))




